<template>
	<view>
		<button @click="clogin" size="default" type="default"
			style="color:#ffffff;backgroundColor:#1AAD19;borderColor:#1AAD19"
			hover-class="is-hover">登录</button>
		<view class="uni-form-item uni-column">
			<view class="title">可自动聚焦的input</view>
			<input class="uni-input" focus placeholder="自动获得焦点" v-model="content" />
		</view>
		<button @click="askn" size="default" type="default"
			style="color:#ffffff;backgroundColor:#1AAD19;borderColor:#1AAD19"
			hover-class="is-hover">问一下</button>
		<input class="uni-input" focus placeholder="自动获得焦点" v-model="answer" />
	</view>
</template>

<script setup>
	import { onMounted, reactive } from 'vue';
	import {wxLogin,backLogin,hello} from '../../utis/api.js'
	import {ref} from 'vue'
	let src = ref("aaaa")
	let websoket = ref();
	const wsUri = ref("ws://127.0.0.1:8080/ws/test")
	let content = ref("")
	let answer = reactive([])
	onMounted(()=>{
		hello().then(res=>{
			console.log(res)
			startws();
		})
	})
	const clogin = ()=>{
		login();
	}
	const login = ()=>{
		wxLogin().then(res=>{
			if(res.errMsg === "login:ok") {
				backLogin({code:res.code}).then(authon=>{
					if(authon.code === 0) {
						uni.setStorage({
							"session_key":authon.session_key,
							"openid":authon.openid
						})
					}
				})
			} else {
				uni.showToast({
					title:"微信登录失败"
				})
			}
		})
	}
	
	const startws = ()=>{
		websoket.value = uni.connectSocket({url:wsUri.value,success() {
			console.log("创建成功")
		},fail() {
			console.log("连接失败")
		},complete() {
			console.log("连接完成")
		}});
		
		websoket.value.onOpen((res)=>{
			console.log(res)
		})
		
		websoket.value.onMessage((res) => {
			let str = res.data.substr(8);
			let data = JSON.parse(str)
			console.log(data.choices[0].delta.content);
			answer+=data.choices[0].delta.content
		});
	}
	
	const askn = ()=>{
		console.log(content.value)
		websoket.value.send({data:content.value});
	}
</script>
<style>
	
</style>
